﻿using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Prism.Events;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;

namespace SoonCode.FocusTest.Views
{
    /// <summary>
    /// AnswerItemGFull.xaml 的交互逻辑
    /// </summary>
    public partial class AnswerItemGFull : UserControl
    {
        private bool isDrawing = false;
        private string testType = "itemG";
        Point currentPoint = new Point();
        private List<Line> lines = new List<Line>();
        private IEventAggregator aggregator;
        private string[] checkColors = ["#FF000000"];
        public HashSet<string> colors;
        public AnswerItemGFull(IEventAggregator aggregator)
        {
            this.aggregator = aggregator;
            this.aggregator.GetEvent<QuestionChangeEvent>().Subscribe(OnQuestionChange);
            InitializeComponent();
        }

        public void OnQuestionChange(EventInfo info)
        {
            if (info.Type != testType) return;
            foreach (Line line in lines)
            {
                drawingCanvas.Children.Remove(line);
            }

            colors = new HashSet<string>();
            questionImg.Source=new BitmapImage(new Uri(info.Data["question"].ToString()));
            
            checkQuestionImg.Source= new BitmapImage(new Uri(info.Data["question"].ToString()));
            drawingCanvas.UpdateLayout();
            EventInfo eventInfo = new EventInfo();
            eventInfo.Type = testType;
            eventInfo.Data["canvas"] = drawingCanvas;
            this.aggregator.GetEvent<StudentAnswerEvent>().Publish(eventInfo);
        }
        private void Drawing_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDrawing = true;
            currentPoint = e.GetPosition(this);
            EventInfo eventInfo = new EventInfo();
            eventInfo.Type = testType;
            eventInfo.Data["canvas"] = drawingCanvas;
            this.aggregator.GetEvent<StudentAnswerEvent>().Publish(eventInfo);
        }

        private void Drawing_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (isDrawing)
            {
                Line line = new Line();

                line.Stroke = Brushes.Black;
                line.StrokeThickness = 2;
                line.X1 = currentPoint.X;
                line.Y1 = currentPoint.Y;
                line.X2 = e.GetPosition(this).X;
                line.Y2 = e.GetPosition(this).Y;
                currentPoint = e.GetPosition(this);
                lines.Add(line);
                drawingCanvas.Children.Add(line);
                EventInfo eventInfo = new EventInfo();
                eventInfo.Type = testType;
                eventInfo.Data["canvas"] = drawingCanvas;
                this.aggregator.GetEvent<StudentAnswerEvent>().Publish(eventInfo);
                GetPixelColor(checkCanvas,line.X1,line.Y1);
                GetPixelColor(checkCanvas, line.X2, line.Y2);
            }
        }
        
        private void Drawing_OnPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDrawing = false;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            EventInfo eventInfo = new EventInfo();
            eventInfo.Type = testType+"_submit";
            
            bool collision = false;
            foreach (string color in colors)
            {
                Trace.WriteLine(color);
                if (checkColors.Contains(color))
                {
                    collision=true;
                    break;
                }

            }
            eventInfo.Data["collision"]= collision;
            this.aggregator.GetEvent<StudentAnswerEvent>().Publish(eventInfo);
        }
        public async void GetPixelColor(Canvas canvas, double x, double y)
        {
            // 创建一个RenderTargetBitmap对象，并设置其宽高
            RenderTargetBitmap renderTarget = new RenderTargetBitmap(
                (int)canvas.ActualWidth,
                (int)canvas.ActualHeight,
                96,
                96,
                PixelFormats.Pbgra32);

            // 使用VisualBrush将Canvas内容渲染到RenderTargetBitmap中
            VisualBrush visualBrush = new VisualBrush(canvas);
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), new Point(canvas.ActualWidth, canvas.ActualHeight)));
            }
            renderTarget.Render(drawingVisual);

            // 从RenderTargetBitmap创建BitmapSource并转换为BitmapPixels
            BitmapSource bitmapSource = renderTarget;
            byte[] pixels = new byte[4 * ((int)(canvas.ActualWidth) * (int)(canvas.ActualHeight))];
            bitmapSource.CopyPixels(pixels, (int)(canvas.ActualWidth) * 4, 0);

            // 计算点(x, y)的颜色
            int index = (int)(y * canvas.ActualWidth * 4) + (int)x * 4;
            byte blue = pixels[index];
            byte green = pixels[index + 1];
            byte red = pixels[index + 2];
            byte alpha = pixels[index + 3];
            colors.Add(Color.FromArgb(alpha, red, green, blue).ToString());
        }
    }
}
